// CatAddin.cpp : Implementation of CCatAddin
#include "stdafx.h"
#include "CatPartner.h"
#include "CatAddin.h"

/////////////////////////////////////////////////////////////////////////////
// CCatAddin

_ATL_FUNC_INFO DocumentOpenInfo = {CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH|VT_BYREF}};
_ATL_FUNC_INFO QuitInfo = {CC_STDCALL, VT_EMPTY, 0};

STDMETHODIMP CCatAddin::OnConnection(IDispatch * Application, ext_ConnectMode ConnectMode, IDispatch * AddInInst, SAFEARRAY * * custom)
{
	HRESULT hr;
	DWORD m_dwCookie = 0;
	if (!m_pInnerUnk)
	{
		hr = RegisterActiveObject(GetControllingUnknown() , CLSID_CatAddin , ACTIVEOBJECT_WEAK, &m_dwCookie);
	}
	CComQIPtr<_Application> spapp(Application);;
	ATLASSERT(spapp);
	m_spApp = spapp;
	hr = AppEvents::DispEventAdvise(m_spApp);

	return hr ;
}

STDMETHODIMP CCatAddin::OnDisconnection (ext_DisconnectMode RemoveMode, SAFEARRAY * * custom)
{
	if(m_spApp){
		AppEvents::DispEventUnadvise(m_spApp);
		m_spApp.Release();
		m_spApp = NULL;
	}
	return S_OK;
}

STDMETHODIMP CCatAddin::OnStartupComplete(SAFEARRAY * * custom)
{
	HRESULT hr;
	m_pPath = GetCurrentPath(); 
	LPCTSTR dotfile = GetCurrentPathFile(FILE_DOT);
	
	if (_taccess(dotfile, 0) == 0)
	{
		CComBSTR bstr( dotfile );
		AddIns* addins; AddIn* addin;
		m_spApp->get_AddIns(&addins);
		hr = addins->Add( bstr, &CComVariant(TRUE), &addin);
		if (SUCCEEDED(hr))
		{
			Templates *templates;  long ncount;
			m_spApp->get_Templates(&templates);
			templates->get_Count(&ncount);
			for (long i= 1; i<=ncount ; i++)
			{
				CComBSTR fullname;
				templates->Item(&CComVariant(i), &m_tmeplatefile);
				m_tmeplatefile->get_FullName(&fullname);
				if (bstr == fullname)
				{
					VARIANT_BOOL saved;
					m_tmeplatefile->get_Saved(&saved);
					if (!(BOOL)saved)
					{
						m_tmeplatefile->Save();
					}
					break;
				}
			}
		}
	}
	return S_OK;
}

void __stdcall CCatAddin::DocumentOpen(IDispatchPtr ptr)
{
	CComQIPtr<_Document> spDoc(ptr);
	ATLASSERT(spDoc);
}
void __stdcall CCatAddin::Quit()
{
	if(m_tmeplatefile){
		VARIANT_BOOL saved;
		m_tmeplatefile->get_Saved(&saved);
		if (!(BOOL)saved)
		{
			m_tmeplatefile->Save();
		}
		m_tmeplatefile->Release();
		m_tmeplatefile = NULL;
	}
}

LPTSTR CCatAddin::GetCurrentPath()
{
	static TCHAR filename[MAXPATH] = {0};
	HINSTANCE h = _Module.GetModuleInstance();
	GetModuleFileName( h , filename , MAXPATH);
	LPTSTR pch;
	pch = _tcsrchr( filename , '\\');
	filename[ pch - filename +1] = 0;
	return filename;
}

LPCTSTR CCatAddin::GetCurrentPathFile( LPCTSTR exe)
{
	static TCHAR filename[MAXPATH] = {0};
	HINSTANCE h = _Module.GetModuleInstance();
	GetModuleFileName( h , filename , MAXPATH);
	int l = _tcslen( filename ) - _tcslen(exe); 
	_tcscpy(filename + l ,  exe ) ;
	return filename;
}
